# -*- coding: utf-8 -*-

"""
更新 SUMMARY.md 文件
"""

import os
import json
import codecs

import constants
import utils


def check():
    """ 数据校验 """
    summary_files_from_structure = sorted(utils.structure_define.parse(constants.BOOKS))
    # for i in summary_files_from_structure:
    #     print i
    summary_files_from_gitmodules = utils.gitmodules.parse(constants.ROOT, ignores='scripts')
    # for i in summary_files_from_gitmodules:
    #     print i
    books_not_add_to_gitmodules = [i for i in summary_files_from_structure if i not in summary_files_from_gitmodules]
    books_not_add_to_structure = [i for i in summary_files_from_gitmodules if i not in summary_files_from_structure]
    if books_not_add_to_gitmodules:
        print '\n'.join(['', '*' * 70, 'Books NOT FOUND in .gitmodules', '*' * 70, ''])
        for i in books_not_add_to_gitmodules:
            print i
        print
    if books_not_add_to_structure:
        print '\n'.join(['', '*' * 70, 'Books NOT FOUND in structure', '*' * 70, ''])
        for i in books_not_add_to_structure:
            print i
        print '\n'.join(['', '*' * 70, ''])
    return not books_not_add_to_gitmodules and not books_not_add_to_structure


def main():
    """ main """
    if not check():
        # 1. 确保 .gitmodules 和 constants.BOOKS 一致
        # 2. 确保 SUMMARY.md 文件存在
        return
    # utils.summary.show(os.path.join(constants.ROOT, 'SUMMARY.md'))
    total_chapters = []
    for book in utils.structure_define.parse(constants.BOOKS):
        # print book
        # show_book(book)
        # continue
        summary_path = os.path.join(constants.ROOT, book, 'SUMMARY.md')
        chapters = utils.summary.parse(summary_path, parent=book)
        # show_chapters(chapters)
        # print '-' * 70
        total_chapters.append(chapters)
    total_chapters = utils.iterchain(total_chapters)
    # print json.dumps(total_chapters, indent=4, ensure_ascii=False)

    book_names = utils.structure_define.get_names(constants.BOOKS)
    chapter_names = [chapter['path'] for chapter in total_chapters]
    chapters = []
    for index, chapter in enumerate(list(chapter_names)):
        _ = chapter.split('/')
        _len = len(_)
        i = 0
        while _len > i + 2:
            _dir = '/'.join(_[:i+1])
            dir_chapter = _dir + '/README.md'
            dir_chapter_path = os.path.join(constants.ROOT, dir_chapter)
            # print dir_chapter
            if not os.path.exists(dir_chapter_path):
                print 'DirChapterNotFound:', dir_chapter_path
            if dir_chapter not in chapter_names:
                level = _dir.count('/')
                print 'AddDirChapter: %s #%s' % (dir_chapter, level)
                chapter_names.append(dir_chapter)
                chapters.append({
                    'path': dir_chapter,
                    'level': level,
                    'title': book_names.get(_dir, _dir),
                })
            i += 1
        chapters.append(total_chapters[index])
    chapters_json = codecs.open(os.path.join(constants.ROOT, 'chapters.json'), 'w', 'utf-8')
    utils.summary.show(chapters)
    utils.summary.write(chapters, constants.ROOT)
    json.dump(chapters, chapters_json, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    main()
